package com.gewu.pm.ui.activity.terminal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.TerminalAddBean;
import com.gewu.pm.http.glide.GlideApp;
import com.gewu.pm.other.GridSpaceDecoration;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.adapter.order.ImageUploadAdapter;
import com.gewu.pm.ui.dialog.AddressDialog;
import com.gewu.pm.ui.dialog.SelectSubmitterDialog;
import com.gewu.pm.ui.dialog.SelectionListDialog;
import com.gewu.pm.utils.TextStarUtils;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.utils.eventbus.EventCode;
import com.hjq.base.BaseDialog;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

/**
 * 新增终端确认页面（第三页）
 */
public final class TerminalAddThreeActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    private static final int MAX_FREEZER_PHOTO_COUNT = 9;  // 冰柜照片最多9张

    // 基本信息
    private TextView mTerminalNameLabel;
    private EditText mTerminalNameEdit;
    private TextView mTerminalCodeLabel;
    private EditText mTerminalCodeEdit;
    private TextView mCooperationStatusLabel;
    private TextView mCooperationStatusValue;
    private TextView mTerminalTypeLabel;
    private TextView mTerminalTypeValue;
    private TextView mPaymentTypeLabel;
    private TextView mPaymentTypeValue;
    private TextView mFacadePhotoLabel;
    private ImageView mFacadePhotoView;
    private ImageView mFacadePhotoDeleteView;
    private String mFacadePhotoPath;
    private TextView mStorePhotoLabel;
    private ImageView mStorePhotoView;
    private ImageView mStorePhotoDeleteView;
    private String mStorePhotoPath;

    // 营业执照
    private CheckBox mTaxInvoiceNoCheckBox;
    private CheckBox mTaxInvoiceYesCheckBox;
    private CheckBox mHasLicenseNoCheckBox;
    private CheckBox mHasLicenseYesCheckBox;
    private RelativeLayout mLayoutHasLicenseContent;
    private RelativeLayout mLayoutNoLicenseContent;
    private TextView mLicensePhotoLabel;
    private ImageView mLicensePhotoView;
    private ImageView mLicensePhotoDeleteView;
    private String mLicensePhotoPath;
    private EditText mRegisterNameEdit;
    private EditText mLicenseNumberEdit;
    private TextView mUploadPhotoLabel;
    private ImageView mUploadPhotoView;
    private ImageView mUploadPhotoDeleteView;
    private String mUploadPhotoPath;
    private EditText mNoteEdit;

    // 配送商信息
    private TextView mSalesAreaLabel;
    private TextView mDeliveryProviderLabel;
    private TextView mSalespersonLabel;
    private TextView mDepartmentLabel;
    private TextView mDeliveryProviderValue;
    private TextView mSalespersonValue;
    private TextView mSalesAreaValue;
    private TextView mDepartmentValue;

    // 冰柜管理
    private EditText mFreezerQuantityEdit;
    private EditText mFreezerPlacedEdit;
    private CheckBox mSubsidyFeeNoCheckBox;
    private CheckBox mSubsidyFeeYesCheckBox;
    private EditText mSubsidyAmountEdit;
    private TextView mFreezerPhotoLabel;
    private RecyclerView mFreezerPhotosView;
    private ImageUploadAdapter mFreezerPhotoAdapter;
    private final List<String> mFreezerPhotoList = new ArrayList<>();

    // 地区
    private TextView mLocationAreaLabel;
    private TextView mDetailedAddressLabel;
    private TextView mLatLngLabel;
    private TextView mLocationAreaValue;
    private EditText mDetailedAddressEdit;
    private TextView mLatLngValue;


    // 提交按钮
    private TextView mSubmitButton;

    // 当前选择的图片类型
    private int mCurrentPhotoType = -1;  // -1-冰柜照片，0-门头照，1-店内照片，2-营业执照图，3-无执照上传图

    // 数据Bean
    private TerminalAddBean mDataBean;

    public static void start(Context context, TerminalAddBean bean) {
        Intent intent = new Intent(context, TerminalAddThreeActivity.class);
        intent.putExtra(IntentKey.DATA, bean);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.add_terminal_three_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle("新增终端");

        // 基本信息
        mTerminalNameLabel = findViewById(R.id.tv_terminal_name_label);
        mTerminalNameEdit = findViewById(R.id.et_terminal_name);
        mTerminalCodeLabel = findViewById(R.id.tv_terminal_code_label);
        mTerminalCodeEdit = findViewById(R.id.et_terminal_code);
        mCooperationStatusLabel = findViewById(R.id.tv_cooperation_status_label);
        mCooperationStatusValue = findViewById(R.id.tv_cooperation_status_value);
        mTerminalTypeLabel = findViewById(R.id.tv_terminal_type_label);
        mTerminalTypeValue = findViewById(R.id.tv_terminal_type_value);
        mPaymentTypeLabel = findViewById(R.id.tv_payment_type_label);
        mPaymentTypeValue = findViewById(R.id.tv_payment_type_value);
        mFacadePhotoLabel = findViewById(R.id.tv_facade_photo_label);
        mFacadePhotoView = findViewById(R.id.iv_facade_photo);
        mFacadePhotoDeleteView = findViewById(R.id.iv_facade_photo_delete);
        mStorePhotoLabel = findViewById(R.id.tv_store_photo_label);
        mStorePhotoView = findViewById(R.id.iv_store_photo);
        mStorePhotoDeleteView = findViewById(R.id.iv_store_photo_delete);

        // 营业执照
        mTaxInvoiceNoCheckBox = findViewById(R.id.cb_tax_invoice_no);
        mTaxInvoiceYesCheckBox = findViewById(R.id.cb_tax_invoice_yes);
        mHasLicenseNoCheckBox = findViewById(R.id.cb_has_license_no);
        mHasLicenseYesCheckBox = findViewById(R.id.cb_has_license_yes);
        mLayoutHasLicenseContent = findViewById(R.id.layout_has_license_content);
        mLayoutNoLicenseContent = findViewById(R.id.layout_no_license_content);
        mLicensePhotoLabel = findViewById(R.id.tv_license_photo_label);
        mLicensePhotoView = findViewById(R.id.iv_license_photo);
        mLicensePhotoDeleteView = findViewById(R.id.iv_license_photo_delete);
        mRegisterNameEdit = findViewById(R.id.et_register_name);
        mLicenseNumberEdit = findViewById(R.id.et_license_number);
        mUploadPhotoLabel = findViewById(R.id.tv_upload_photo_label);
        mUploadPhotoView = findViewById(R.id.iv_upload_photo);
        mUploadPhotoDeleteView = findViewById(R.id.iv_upload_photo_delete);
        mNoteEdit = findViewById(R.id.et_note);

        // 配送商信息
        mSalesAreaLabel = findViewById(R.id.tv_sales_area_label);
        mDeliveryProviderLabel = findViewById(R.id.tv_delivery_provider_label);
        mSalespersonLabel = findViewById(R.id.tv_salesperson_label);
        mDepartmentLabel = findViewById(R.id.tv_department_label);
        mDeliveryProviderValue = findViewById(R.id.tv_delivery_provider_value);
        mSalespersonValue = findViewById(R.id.tv_salesperson_value);
        mSalesAreaValue = findViewById(R.id.tv_sales_area_value);
        mDepartmentValue = findViewById(R.id.tv_department_value);

        // 冰柜管理
        mFreezerQuantityEdit = findViewById(R.id.et_freezer_quantity);
        mFreezerPlacedEdit = findViewById(R.id.et_freezer_placed);
        mSubsidyFeeNoCheckBox = findViewById(R.id.cb_subsidy_fee_no);
        mSubsidyFeeYesCheckBox = findViewById(R.id.cb_subsidy_fee_yes);
        mSubsidyAmountEdit = findViewById(R.id.et_subsidy_amount);
        mFreezerPhotoLabel = findViewById(R.id.tv_freezer_photo_label);
        mFreezerPhotosView = findViewById(R.id.rv_freezer_photos);

        // 地区
        mLocationAreaLabel = findViewById(R.id.tv_location_area_label3);
        mDetailedAddressLabel = findViewById(R.id.tv_detailed_address_label3);
        mLatLngLabel = findViewById(R.id.tv_lat_lng_label3);
        mLocationAreaValue = findViewById(R.id.tv_location_area_value3);
        mDetailedAddressEdit = findViewById(R.id.et_detailed_address3);
        mLatLngValue = findViewById(R.id.tv_lat_lng_value3);

        // 提交按钮（使用内部按钮 ID）
        mSubmitButton = findViewById(R.id.tv_bottom_button);

        // 设置必填标记
        TextStarUtils.setRequiredText(mTerminalNameLabel, getString(R.string.terminal_name));
        TextStarUtils.setRequiredText(mTerminalCodeLabel, getString(R.string.terminal_code));
        TextStarUtils.setRequiredText(mCooperationStatusLabel, getString(R.string.cooperation_status));
        TextStarUtils.setRequiredText(mTerminalTypeLabel, getString(R.string.terminal_type));
        TextStarUtils.setRequiredText(mPaymentTypeLabel, getString(R.string.payment_type));
        TextStarUtils.setRequiredText(mFacadePhotoLabel, getString(R.string.facade_photo));
        TextStarUtils.setRequiredText(mStorePhotoLabel, getString(R.string.store_photo));

        // 配送商信息和地区模块的必填标记
        TextStarUtils.setRequiredText(mSalesAreaLabel, getString(R.string.sales_area));
        TextStarUtils.setRequiredText(mDeliveryProviderLabel, "配送商");
        TextStarUtils.setRequiredText(mSalespersonLabel, "业务员");
        TextStarUtils.setRequiredText(mDepartmentLabel, "部门");
        TextStarUtils.setRequiredText(mLocationAreaLabel, getString(R.string.location_area));
        TextStarUtils.setRequiredText(mDetailedAddressLabel, getString(R.string.detailed_address));
        TextStarUtils.setRequiredText(mLatLngLabel, getString(R.string.latitude_longitude));

        // 设置CheckBox互斥逻辑
        setupCheckBoxGroup(mTaxInvoiceNoCheckBox, mTaxInvoiceYesCheckBox);
        setupCheckBoxGroup(mSubsidyFeeNoCheckBox, mSubsidyFeeYesCheckBox);
        
        // 设置有无执照单选逻辑（需要同时处理布局切换）
        setupHasLicenseCheckBoxGroup();

        // 默认显示无营业执照布局
        updateLicenseLayout(false);

        // 设置图片点击事件
        mFacadePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 0;  // 门头照
            ImageSelectActivity.start(this, 1, this);
        });
        mStorePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 1;  // 店内照片
            ImageSelectActivity.start(this, 1, this);
        });
        mLicensePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 2;  // 营业执照图
            ImageSelectActivity.start(this, 1, this);
        });
        mUploadPhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 3;  // 无执照上传图
            ImageSelectActivity.start(this, 1, this);
        });

        // 设置图片删除按钮点击事件
        mFacadePhotoDeleteView.setOnClickListener(v -> deleteFacadePhoto());
        mStorePhotoDeleteView.setOnClickListener(v -> deleteStorePhoto());
        mLicensePhotoDeleteView.setOnClickListener(v -> deleteLicensePhoto());
        mUploadPhotoDeleteView.setOnClickListener(v -> deleteUploadPhoto());

        // 初始化冰柜照片网格（3列）
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mFreezerPhotosView.setLayoutManager(gridLayoutManager);
        // 添加分割线间距（3dp）
        mFreezerPhotosView.addItemDecoration(new GridSpaceDecoration((int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics())));

        // 设置冰柜照片适配器
        mFreezerPhotoAdapter = new ImageUploadAdapter(this, MAX_FREEZER_PHOTO_COUNT, position -> {
            // 删除图片
            mFreezerPhotoList.remove(position);
            updateFreezerPhotoList();
        });
        // 设置占位图为 add_ic
        mFreezerPhotoAdapter.setPlaceholderResId(R.drawable.add_ic);
        // 启用占位文字显示
        mFreezerPhotoAdapter.setShowPlaceholderText(true);
        mFreezerPhotoAdapter.setPlaceholderTextPrefix("上传图片");

        // 设置添加图片监听
        mFreezerPhotoAdapter.setOnAddListener(() -> {
            // 打开图片选择
            int remainCount = MAX_FREEZER_PHOTO_COUNT - mFreezerPhotoList.size();
            if (remainCount > 0) {
                mCurrentPhotoType = -1;  // 标记为冰柜照片
                ImageSelectActivity.start(this, remainCount, this);
            } else {
                toast("最多只能选择" + MAX_FREEZER_PHOTO_COUNT + "张图片");
            }
        });

        mFreezerPhotosView.setAdapter(mFreezerPhotoAdapter);

        // 设置点击事件
        setOnClickListener(mCooperationStatusValue, mTerminalTypeValue, mPaymentTypeValue,
                mDeliveryProviderValue, mLocationAreaValue, mLatLngValue, mSubmitButton);
    }

    @Override
    protected void initData() {
        // 接收数据Bean
        Serializable data = getSerializable(IntentKey.DATA);
        if (data instanceof TerminalAddBean) {
            mDataBean = (TerminalAddBean) data;
            fillData();
        }

        // 初始化冰柜照片列表
        updateFreezerPhotoList();
    }

    /**
     * 填充数据
     */
    private void fillData() {
        if (mDataBean == null) return;

        // 基本信息
        if (!TextUtils.isEmpty(mDataBean.getTerminalName())) {
            mTerminalNameEdit.setText(mDataBean.getTerminalName());
        }
        if (!TextUtils.isEmpty(mDataBean.getTerminalCode())) {
            mTerminalCodeEdit.setText(mDataBean.getTerminalCode());
        }
        if (!TextUtils.isEmpty(mDataBean.getSalesArea())) {
            mSalesAreaValue.setText(mDataBean.getSalesArea());
        }
        if (!TextUtils.isEmpty(mDataBean.getTerminalType())) {
            mTerminalTypeValue.setText(mDataBean.getTerminalType());
        }
        mFacadePhotoPath = mDataBean.getFacadePhotoPath();
        if (!TextUtils.isEmpty(mFacadePhotoPath)) {
            updateFacadePhoto();
        }
        mStorePhotoPath = mDataBean.getStorePhotoPath();
        if (!TextUtils.isEmpty(mStorePhotoPath)) {
            updateStorePhoto();
        }

        // 地区
        if (!TextUtils.isEmpty(mDataBean.getLocationArea())) {
            mLocationAreaValue.setText(mDataBean.getLocationArea());
        }
        if (!TextUtils.isEmpty(mDataBean.getDetailedAddress())) {
            mDetailedAddressEdit.setText(mDataBean.getDetailedAddress());
        }
        if (!TextUtils.isEmpty(mDataBean.getLatLng())) {
            mLatLngValue.setText(mDataBean.getLatLng());
        }

        // 冰柜照片
        if (mDataBean.getFreezerPhotoList() != null) {
            mFreezerPhotoList.addAll(mDataBean.getFreezerPhotoList());
            updateFreezerPhotoList();
        }
    }

    /**
     * 设置CheckBox互斥逻辑（单选，必须选中一个）
     */
    private void setupCheckBoxGroup(CheckBox checkBox1, CheckBox checkBox2) {
        checkBox1.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 选中checkBox1时，取消checkBox2
                checkBox2.setChecked(false);
            } else {
                // 尝试取消checkBox1时，如果checkBox2也是未选中状态，则强制选中checkBox1（必须选中一个）
                if (!checkBox2.isChecked()) {
                    checkBox1.setChecked(true);
                }
            }
        });

        checkBox2.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 选中checkBox2时，取消checkBox1
                checkBox1.setChecked(false);
            } else {
                // 尝试取消checkBox2时，如果checkBox1也是未选中状态，则强制选中checkBox2（必须选中一个）
                if (!checkBox1.isChecked()) {
                    checkBox2.setChecked(true);
                }
            }
        });
    }

    /**
     * 设置有无执照单选逻辑（必须选中一个，同时处理布局切换）
     */
    private void setupHasLicenseCheckBoxGroup() {
        mHasLicenseNoCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 选中"无"时，取消"有"，并更新布局
                mHasLicenseYesCheckBox.setChecked(false);
                updateLicenseLayout(false);
            } else {
                // 尝试取消"无"时，如果"有"也是未选中状态，则强制选中"无"（必须选中一个）
                if (!mHasLicenseYesCheckBox.isChecked()) {
                    mHasLicenseNoCheckBox.setChecked(true);
                }
            }
        });

        mHasLicenseYesCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 选中"有"时，取消"无"，并更新布局
                mHasLicenseNoCheckBox.setChecked(false);
                updateLicenseLayout(true);
            } else {
                // 尝试取消"有"时，如果"无"也是未选中状态，则强制选中"有"（必须选中一个）
                if (!mHasLicenseNoCheckBox.isChecked()) {
                    mHasLicenseYesCheckBox.setChecked(true);
                }
            }
        });
    }

    /**
     * 更新营业执照布局显示
     */
    private void updateLicenseLayout(boolean hasLicense) {
        if (hasLicense) {
            // 有营业执照：显示营业执照图、注册名称、营业执照号
            mLayoutHasLicenseContent.setVisibility(View.VISIBLE);
            mLayoutNoLicenseContent.setVisibility(View.GONE);
        } else {
            // 无营业执照：显示上传图片、备注
            mLayoutHasLicenseContent.setVisibility(View.GONE);
            mLayoutNoLicenseContent.setVisibility(View.VISIBLE);
        }
    }

    private String mProvince = "浙江省";//省
    private String mCity = "杭州市";//市
    private String mArea = "滨江区";//区
    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mCooperationStatusValue) {
            // 选择合作状态
            List<String> options = new ArrayList<>();
            options.add("合作中");
            options.add("终止合作");
            new SelectionListDialog.Builder(this)
                    .setTitle("请选择合作状态")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mCooperationStatusValue.setText(selectedItem);
                        }
                    })
                    .show();
        } else if (view == mTerminalTypeValue) {
            // 选择终端类型
            List<String> options = new ArrayList<>();
            options.add("超市");
            options.add("生鲜店");
            options.add("餐饮店");
            options.add("副食品店");
            options.add("水果店");
            options.add("企事业单位");
            options.add("早餐豆奶");
            options.add("农贸");
            options.add("预制菜");
            options.add("腐乳类");
            new SelectionListDialog.Builder(this)
                    .setTitle("请选择终端类型")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mTerminalTypeValue.setText(selectedItem);
                        }
                    })
                    .show();
        } else if (view == mPaymentTypeValue) {
            // 选择支付类型
            toast("选择支付类型");
            // TODO: 打开支付类型选择
        } else if (view == mDeliveryProviderValue) {
            // 选择配送商
            new SelectSubmitterDialog.Builder(this,101)//101 = 只显示配送商
                    .setListener(new SelectSubmitterDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String submitter, int type, Object data) {
                            // 显示选中的提交人
                            mDeliveryProviderValue.setText(submitter);
                            mDeliveryProviderValue.setTextColor(getResources().getColor(R.color.cb3));
                        }
                    })
                    .show();
        } else if (view == mLocationAreaValue) {
            // 选择所在地区
            new AddressDialog.Builder(this)
                    //.setTitle("选择地区")
                    // 设置默认省份
                    .setProvince(mProvince)
                    // 设置默认城市（必须要先设置默认省份）
                    .setCity(mCity)
                    // 不选择县级区域
                    //.setIgnoreArea()
                    .setListener((dialog, province, city, area) -> {
                        String address = province + city + area;
                        if (!mLocationAreaValue.getText().equals(address)) {
                            mProvince = province;
                            mCity = city;
                            mArea = area;
                            mLocationAreaValue.setText(address);
                        }
                    })
                    .show();
        } else if (view == mLatLngValue) {
            // 获取经纬度
            toast("点击获取经纬度");
            // TODO: 获取经纬度
        } else if (view == mSubmitButton) {
            // 提交
            submit();
        }
    }

    /**
     * 提交
     */
    private void submit() {
        // TODO: 验证必填项

        // 收集所有数据到 Bean
        TerminalAddBean bean = new TerminalAddBean();

        // 基本信息
        bean.setTerminalName(mTerminalNameEdit.getText().toString().trim());
        bean.setTerminalCode(mTerminalCodeEdit.getText().toString().trim());
        bean.setCooperationStatus(mCooperationStatusValue.getText().toString().trim());
        bean.setTerminalType(mTerminalTypeValue.getText().toString().trim());
        bean.setPaymentType(mPaymentTypeValue.getText().toString().trim());
        bean.setFacadePhotoPath(mFacadePhotoPath);
        bean.setStorePhotoPath(mStorePhotoPath);

        // 营业执照
        bean.setTaxInvoice(mTaxInvoiceYesCheckBox.isChecked());
        bean.setHasLicense(mHasLicenseYesCheckBox.isChecked());
        bean.setLicensePhotoPath(mLicensePhotoPath);
        bean.setRegisterName(mRegisterNameEdit.getText().toString().trim());
        bean.setLicenseNumber(mLicenseNumberEdit.getText().toString().trim());
        bean.setNote(mNoteEdit.getText().toString().trim());
        bean.setUploadPhotoPath(mUploadPhotoPath);

        // 配送商信息
        bean.setDeliveryProvider(mDeliveryProviderValue.getText().toString().trim());
        bean.setSalesperson(mSalespersonValue.getText().toString().trim());
        bean.setSalesArea(mSalesAreaValue.getText().toString().trim());
        bean.setDepartment(mDepartmentValue.getText().toString().trim());

        // 冰柜管理
        bean.setFreezerQuantity(mFreezerQuantityEdit.getText().toString().trim());
        bean.setFreezerPlaced(mFreezerPlacedEdit.getText().toString().trim());
        bean.setSubsidyFee(mSubsidyFeeYesCheckBox.isChecked());
        bean.setSubsidyAmount(mSubsidyAmountEdit.getText().toString().trim());
        bean.setFreezerPhotoList(new ArrayList<>(mFreezerPhotoList));

        // 地区
        bean.setLocationArea(mLocationAreaValue.getText().toString().trim());
        bean.setDetailedAddress(mDetailedAddressEdit.getText().toString().trim());
        bean.setLatLng(mLatLngValue.getText().toString().trim());

        // 联系人列表（从第二页传递过来的）
        if (mDataBean != null && mDataBean.getContactList() != null) {
            bean.setContactList(mDataBean.getContactList());
        }

        // 打印所有数据
        Timber.d("==========  ==========");
        Timber.d("基本信息:");
        Timber.d("  终端名称: %s", bean.getTerminalName());
        Timber.d("  终端编码: %s", bean.getTerminalCode());
        Timber.d("  合作状态: %s", bean.getCooperationStatus());
        Timber.d("  终端类型: %s", bean.getTerminalType());
        Timber.d("  支付类型: %s", bean.getPaymentType());
        Timber.d("  门头照: %s", bean.getFacadePhotoPath());
        Timber.d("  店内照片: %s", bean.getStorePhotoPath());
        Timber.d("营业执照:");
        Timber.d("  对公开票: %s", bean.isTaxInvoice() ? "是" : "否");
        Timber.d("  有无执照: %s", bean.isHasLicense() ? "有" : "无");
        Timber.d("  营业执照图: %s", bean.getLicensePhotoPath());
        Timber.d("  注册名称: %s", bean.getRegisterName());
        Timber.d("  营业执照号: %s", bean.getLicenseNumber());
        Timber.d("  备注: %s", bean.getNote());
        Timber.d("  上传图片: %s", bean.getUploadPhotoPath());
        Timber.d("配送商信息:");
        Timber.d("  配送商: %s", bean.getDeliveryProvider());
        Timber.d("  业务员: %s", bean.getSalesperson());
        Timber.d("  销售区域: %s", bean.getSalesArea());
        Timber.d("  部门: %s", bean.getDepartment());
        Timber.d("冰柜管理:");
        Timber.d("  冰柜数量: %s", bean.getFreezerQuantity());
        Timber.d("  投放冰柜数: %s", bean.getFreezerPlaced());
        Timber.d("  补贴费用: %s", bean.isSubsidyFee() ? "是" : "否");
        Timber.d("  补贴金额: %s", bean.getSubsidyAmount());
        Timber.d("  冰柜照片: %s", bean.getFreezerPhotoList());
        Timber.d("地区:");
        Timber.d("  所在地区: %s", bean.getLocationArea());
        Timber.d("  详细地址: %s", bean.getDetailedAddress());
        Timber.d("  经纬度: %s", bean.getLatLng());
        Timber.d("联系人列表: %s", bean.getContactList());
        Timber.d("====================================");

        // 提交成功
        toast("提交成功");

        // 发送 EventBus 事件通知前两页关闭
        EventBusUtil.sendEvent(new EventBean<>(EventCode.SALES_LEAD_ADDED));

        // 关闭当前页面（前两页会通过 EventBus 自动关闭）
        finish();
    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            if (mCurrentPhotoType == -1) {
                // 冰柜照片（多张）
                mFreezerPhotoList.addAll(images);
                updateFreezerPhotoList();
            } else {
                // 单张图片
                String selectedImage = images.get(0);
                if (mCurrentPhotoType == 0) {
                    // 门头照
                    mFacadePhotoPath = selectedImage;
                    updateFacadePhoto();
                } else if (mCurrentPhotoType == 1) {
                    // 店内照片
                    mStorePhotoPath = selectedImage;
                    updateStorePhoto();
                } else if (mCurrentPhotoType == 2) {
                    // 营业执照图
                    mLicensePhotoPath = selectedImage;
                    updateLicensePhoto();
                } else if (mCurrentPhotoType == 3) {
                    // 无执照上传图
                    mUploadPhotoPath = selectedImage;
                    updateUploadPhoto();
                }
            }
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }

    /**
     * 更新门头照显示
     */
    private void updateFacadePhoto() {
        if (!TextUtils.isEmpty(mFacadePhotoPath) && new File(mFacadePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mFacadePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mFacadePhotoView);
            mFacadePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mFacadePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mFacadePhotoView.setImageResource(R.drawable.add_ic);
            mFacadePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mFacadePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 更新店内照片显示
     */
    private void updateStorePhoto() {
        if (!TextUtils.isEmpty(mStorePhotoPath) && new File(mStorePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mStorePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mStorePhotoView);
            mStorePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mStorePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mStorePhotoView.setImageResource(R.drawable.add_ic);
            mStorePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mStorePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 更新营业执照图显示
     */
    private void updateLicensePhoto() {
        if (!TextUtils.isEmpty(mLicensePhotoPath) && new File(mLicensePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mLicensePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mLicensePhotoView);
            mLicensePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mLicensePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mLicensePhotoView.setImageResource(R.drawable.add_ic);
            mLicensePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mLicensePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 更新无执照上传图显示
     */
    private void updateUploadPhoto() {
        if (!TextUtils.isEmpty(mUploadPhotoPath) && new File(mUploadPhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mUploadPhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mUploadPhotoView);
            mUploadPhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mUploadPhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mUploadPhotoView.setImageResource(R.drawable.add_ic);
            mUploadPhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mUploadPhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 更新冰柜照片列表
     */
    private void updateFreezerPhotoList() {
        List<String> displayList = new ArrayList<>(mFreezerPhotoList);

        // 如果未满9张，添加相机图标
        if (mFreezerPhotoList.size() < MAX_FREEZER_PHOTO_COUNT) {
            displayList.add("camera");
        }

        mFreezerPhotoAdapter.setData(displayList);
    }

    /**
     * 删除门头照
     */
    @SingleClick
    private void deleteFacadePhoto() {
        mFacadePhotoPath = null;
        updateFacadePhoto();
        toast("已删除门头照");
    }

    /**
     * 删除店内照片
     */
    @SingleClick
    private void deleteStorePhoto() {
        mStorePhotoPath = null;
        updateStorePhoto();
        toast("已删除店内照片");
    }

    /**
     * 删除营业执照照片
     */
    @SingleClick
    private void deleteLicensePhoto() {
        mLicensePhotoPath = null;
        updateLicensePhoto();
        toast("已删除营业执照照片");
    }

    /**
     * 删除无执照上传照片
     */
    @SingleClick
    private void deleteUploadPhoto() {
        mUploadPhotoPath = null;
        updateUploadPhoto();
        toast("已删除照片");
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;  // 启用 EventBus
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
    }
}

